package com.zto.sch.advance.aqs;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @program: sch-diy-parent
 * @description:
 * @author: sch
 * @create: 2021-01-11 17:57
 **/
public class MyLock_AQS implements Lock {

    private Sycn sync = new Sycn();

    @Override
    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return null;
    }

    private class Sycn extends AbstractQueuedLongSynchronizer {

        @Override
        protected boolean tryAcquire(long arg) {
            assert arg == 1;
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @SneakyThrows
        @Override
        protected boolean tryRelease(long arg) {
            assert arg == 1;
            if (!isHeldExclusively()) {
                throw new IllegalAccessException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        @Override
        protected boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }


    }
}
